package cn.hackcloud.mutithread;

import java.util.concurrent.TimeUnit;

/**
 * 死锁编码及问题定位
 * 死锁是指 两个及两个以上的进程在执行过程中，因互相争抢资源而造成一种互相等待的现象，若无外力干涉他们都将无法拖进下去
 * jps -l 查看线程执行信息
 * jstack +端口号 查看堆栈信息
 */
public class HoldLockDemo {
    public static void main(String[] args) {
        String lockA = "A";
        String lockB = "B";
        new Thread(new HoldLockThread(lockA, lockB), "AAA").start();
        new Thread(new HoldLockThread(lockB, lockA), "BBB").start();
    }
}

class HoldLockThread implements Runnable {
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "持有" + lockA + "锁、尝试获得" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "持有" + lockB + "锁、尝试获得" + lockA);
            }
        }
    }
}